package com.test.libs.api;

import com.google.gson.JsonObject;
import com.test.framework.rest.RestAPIBase;
import com.test.utils.Tools;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.*;

public class MallAPI extends RestAPIBase {
    String baseURL;
    String token = null;
    HashMap<String, String> header = new HashMap<>();
    JsonObject config;

    public MallAPI() throws IOException {
        //配置导入
        String configFullPath = System.getenv("mall_config");
        if(configFullPath == null){
            throw new IOException("Can not find mall config file, please set it's fullpath by environment variable mall_config!");
        }
        config = Tools.readJsonFile(configFullPath);
        baseURL = Tools.deepGetJsonStringVal(config, new String[]{"base_url"}
                , "default_url");
    }

    public void setToken(String token) {
        header.put("token", token);
    }

    public Map<String, Object> login(String username, String password) throws IOException, JSONException {
        String url = baseURL + "/api/v1/user/login";
        String json = "{" +
                "\"loginName\": \"" + username + "\"," +
                "\"passwordMd5\": \"" + password + "\"" +
                "}";

        Map<String, Object> resp = Post(url, header, null, json);
        JSONObject respBody = (JSONObject) resp.get("body");
        if (respBody.get("resultCode").equals(200)) {
            token = (String) respBody.get("data");
            header.put("token", token);
        }
        return resp;
    }

    public Map<String, Object> dashboard() throws IOException, JSONException {
        String url = baseURL + "/api/v1/index-infos";
        return Get(url, header, null);
    }

    public Map<String, Object> goodsDetail(String id) throws IOException, JSONException {
        String url = baseURL + "/api/v1/goods/detail/" + id;
        return Get(url, header, null);
    }


}
